﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Commons.Responses;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.WebAPI.Common;
using ContactSMS.WebAPI.Controllers.Request;
using ContactSMS.WebAPI.Controllers.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class MessageSessionController : ControllerBase
    {
        private readonly IMessageSessionRepository _messageSessionRepository;
        private readonly IPhoneRepository _phoneRepository;
        private readonly IMessageRepository _messageRepository;
        private readonly TokenService _tokenService;

        public MessageSessionController(IMessageSessionRepository messageSessionRepository, IPhoneRepository phoneRepository, IMessageRepository messageRepository, TokenService tokenService)
        {
            this._messageSessionRepository = messageSessionRepository;
            this._phoneRepository = phoneRepository;
            this._messageRepository = messageRepository;
            this._tokenService = tokenService;
        }

        [HttpGet]
        public async Task<IActionResult> GetMessageSessions([FromQuery] MessageSessionQueryParameters parameters, int page = 1, int pageSize = 10)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            try
            {
                var sessions = await _messageSessionRepository.GetMessageSessionsAsync(parameters, page, pageSize, userId);
                var resp = new ServiceResponse<MessageSessionSearchResponse>()
                {
                    Data = new MessageSessionSearchResponse
                    {
                        list = sessions.MessageSessions,
                        CurrentPage = page,
                        Pages = (int)sessions.TotalPages
                    }
                };
                return Ok(resp);
            }
            catch (Exception ex)
            {
                ServiceResponse<List<MessageSession>> resp = new ServiceResponse<List<MessageSession>>();
                resp.Success = false;
                resp.Message = "暂无数据";
                return StatusCode(500, resp);
            }
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] AddMessageSessionRequest addMessageSessionRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            long ContactId = 0;
            var Phone = await _phoneRepository.GetPhoneByMobileAsync(addMessageSessionRequest.Mobile);
            if (Phone != null)
            {
                ContactId = Phone.ContactId;
            }
            var model = new MessageSession(addMessageSessionRequest.Mobile, addMessageSessionRequest.Desc, ContactId, userId);

            var existing = await _messageSessionRepository.GetMessageSessionByMobileAsync(addMessageSessionRequest.Mobile);
            long messageSessionId = 0;
            if (existing != null)
            {
                await _messageSessionRepository.UpdateMessageSessionAsync(existing.Id, model);
                messageSessionId = existing.Id;
            }
            else
            {
                await _messageSessionRepository.AddMessageSessionAsync(model);
                messageSessionId = model.Id;
            }
            model.Id = messageSessionId;
            var MessageModel = new Message(messageSessionId, addMessageSessionRequest.Desc, addMessageSessionRequest.IsRead, ContactId);
            await _messageRepository.AddMessageAsync(MessageModel);
            ServiceResponse<MessageSession> resp = new ServiceResponse<MessageSession> { Data = model };
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> Synch([FromBody] SynchMessageSessionRequest synchMessageSessionRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }

            foreach (var item in synchMessageSessionRequest.MessageSessions)
            {
                long ContactId = 0;
                var Phone = await _phoneRepository.GetPhoneByMobileAsync(item.Mobile);
                if (Phone != null)
                {
                    ContactId = Phone.ContactId;
                }
                var model = new MessageSession(item.Mobile, item.Desc, ContactId, userId);

                var existing = await _messageSessionRepository.GetMessageSessionByMobileAsync(item.Mobile);
                long messageSessionId;
                if (existing != null)
                {
                    await _messageSessionRepository.UpdateMessageSessionAsync(existing.Id, model);
                    messageSessionId = existing.Id;
                }
                else
                {
                    await _messageSessionRepository.AddMessageSessionAsync(model);
                    messageSessionId = model.Id;
                }
                var MessageModel = new Message(messageSessionId, item.Desc, item.IsRead, ContactId);
                await _messageRepository.AddMessageAsync(MessageModel);
            }
            ServiceResponse<bool> resp = new ServiceResponse<bool> { Success = false, Message = "同步成功" };
            return Ok(resp);
        }

        [HttpDelete]
        [Route("{id:long}")]
        public async Task<IActionResult> DeleteById([FromRoute] long id)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            var result = await _messageSessionRepository.DeleteMessageSessionByIdAsync(id);
            if (result == false)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            await _messageRepository.DeleteMessageByMessageSessionIdAsync(id);
            resp.Success = true;
            resp.Message = "删除成功";
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> DeleteByIds([FromBody] List<long> ids)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            if (ids == null || ids.Count == 0)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return BadRequest(resp);
            }
            var deletedMessages = await _messageSessionRepository.DeleteMessageSessionByIdsAsync(ids.ToArray());
            if (deletedMessages == false)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            await _messageRepository.DeleteMessageByMessageSessionIdsAsync(ids.ToArray());
            resp.Success = true;
            resp.Message = "删除成功";
            return Ok(resp);
        }
    }
}
